<?php

namespace app\common\model\base;

use app\common\model\BaseModel;

class AttachmentGroupModel extends BaseModel
{

    protected $table = 'attachment_group';

    /**
     * 添加
     * @param $data
     * @return AttachmentGroupModel|\think\Model
     * @throws \Exception
     */
    public function add($data)
    {
        $info = $this->where('group_name', $data['group_name'])->find();
        if ($info) exception('分组名称已存在');
        return self::create($data);
    }

    /**
     * 编辑
     * @param $data
     * @return AttachmentGroupModel
     * @throws \Exception
     */
    public function edit($data)
    {
        $info = $this->where('id', $data['id'])->find();
        if ($data['group_name'] != $info['group_name'] && $this->where('group_name', $data['group_name'])->find()) {
            exception('分组名称已存在');
        }
        return self::update($data);
    }

    /**
     * 删除分组
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function del($id)
    {
        $files = AttachmentModel::where('group_id', $id)->find();
        if (!empty($files)) exception('分组下还存在文件，不允许删除！');
        $this->where('id', $id)->delete();
        return true;
    }

    /**
     * 格式化列表
     * @param $list
     * @return array
     */
    public function _formatList($list)
    {
        $groupCount = AttachmentModel::group('group_id')->column('count(*)', 'group_id');
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['file_num'] = 0;
                if (isset($groupCount[$v['id']])) {
                    $list[$k]['file_num'] = $groupCount[$v['id']];
                }
            }
        }
        $list[] = ['id' => 0, 'group_name' => '无分组', 'file_num' => $groupCount[0] ?? 0];
        return $list;
    }
}